{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Probability and Random Processes\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction\n",
    "\n",
    "In this chapter, you'll learn about how to use randomness and probability with code.\n",
    "\n",
    "If you're running this code (either by copying and pasting it, or by downloading it using the icons at the top of the page), you may need to install the packages first. There's a brief guide on installing packages in the Chapter on {ref}`code-preliminaries`.\n",
    "\n",
    "### Imports\n",
    "\n",
    "First we need to import the packages we'll be using"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import scipy.stats as st\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Set max rows displayed for readability\n",
    "pd.set_option(\"display.max_rows\", 6)\n",
    "# Plot settings\n",
    "plt.style.use(\n",
    "    \"https://github.com/aeturrell/coding-for-economists/raw/main/plot_style.txt\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Probability (definitions)\n",
    "\n",
    "Let's get the jargon and definitions out of the way first, then we'll find out a bit about random numbers in code, then we'll actually see how to *use* random numbers for probability!\n",
    "\n",
    "Any probabilistic event can be considered to have three components: the sample space of possible outcomes $\\Omega$, the set of possible events $\\mathcal{F}$, and a probability measure $P$. Furthermore, $A$ is often used to denote a subset of $\\Omega$ and $A^c$ the complement of $A$, while individual events in $\\Omega$ are $\\omega$. In the classic example of rolling a 6-sided fair die once, $\\Omega = \\{1, 2, 3, 4, 5, 6\\}$. If $A = \\{1, 2, 3\\}$ then, by definition of $\\Omega$, $A^c = \\{4, 5, 6\\}$. The probability measure of any sample space satisfies $P(\\Omega)=1$ and $P(\\varnothing)$ = 0.\n",
    "\n",
    "The most important examples of probability that arise in economics are **continuous random variables** and **discrete random variables**. A random variable is a function $X: \\Omega \\rightarrow \\mathbb{R}$ such that $\\{ \\omega \\in \\Omega: X(w) \\leq x\\} \\in \\mathcal{F}$ for each $x\\in\\mathbb{R}$. All this is saying is that for every possible outcome, the random variable is a mapping of that outcome into a well-defined space of real numbers. It makes the connection between outcomes, events, and real numbers.\n",
    "\n",
    "Now we'll go on to more practical matters: discrete and continuous random variables.\n",
    "\n",
    "### Discrete random variables\n",
    "\n",
    "A random variable is discrete if it only takes values in a countable subset of $\\mathbb{R}$; think the integers, or $x\\in\\{0, 1\\}$. The distribution of such values is given by the **probability mass function**, or pmf. The pmf is an object that tells us the probabilty mass given to specific outcomes. The more precise defintion is\n",
    "\n",
    "$$\n",
    "p(x_i) = P(X=x_i) = P(\\underbrace{\\{\\omega\\in \\Omega\\ |\\ X(\\omega) = x_i\\}}_{\\text{set of outcomes resulting in}\\ X=x_i}).\n",
    "$$\n",
    "\n",
    "It has a few key properties. $p:\\mathbb{R} \\rightarrow [0, 1]$, the probability of all outcomes sum to 1, ie $\\displaystyle{\\sum_{x_i} p(x_i)}=1$, the probabilities satisfy $p(x_i) \\geq 0  \\quad\\forall x_i$, and $P(X \\in A) = \\displaystyle\\sum_{x_i \\in A} p(x_i)$. A fair six-sided die is the canonical example.\n",
    "\n",
    "Another useful object is the **cumulative distribution function**, which is defined generally as $\\text{cdf}(x) = P(X \\leq x)\\quad \\forall x \\in \\mathbb{R}$. For probability mass functions, this becomes\n",
    "\n",
    "$$\n",
    "\\text{cdf}(x) = P(X\\leq x) = \\sum_{x_i\\leq x} p(x_i)\n",
    "$$\n",
    "\n",
    "\n",
    "\n",
    "### Continuous random variables\n",
    "\n",
    "Continuous random variables are functions such that $f: \\mathbb{R} \\rightarrow [0, \\infty)$ is a **probability density**. Probability density functions are to continuous random variables what PMFs are to discrete random variables, though there are some important differences that can trip up even the most careful. They are defined as follows: the probability of $X$ taking a value betwen $a$ and $b$ is given by\n",
    "\n",
    "$$\n",
    "P(a \\leq X \\leq b) = \\displaystyle\\int_a^b f(x) dx\n",
    "$$\n",
    "\n",
    "where $f(x)\\geq 0 \\quad \\forall x \\in \\mathbb{R}$, $f$ is piecewise continuous, and $\\displaystyle\\int_{-\\infty}^\\infty f(x) dx = 1$.\n",
    "\n",
    "The big mistake that people sometimes make is to think that $f(x)$ is a probability but it's not! The clue is in the name; $f(x)$ is a probability *density*, while $f(x) dx$ is a probability. This means you only get a probability from $f(x)$ once you integrate it. It also means that $f(x)$ has units of $1/x$. For example, if $x$ is wages, $f(x)$ has units of $\\text{wages}^{-1}$.\n",
    "\n",
    "Cumulative distribution functions are also defined for pdfs:\n",
    "\n",
    "$$\n",
    "\\text{cdf}(x) = P(X\\leq x) = \\int\\limits^x_{-\\infty}\\! f(x')\\, dx'\n",
    "$$\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## Distribution functions\n",
    "\n",
    "Let's now see how code can help us when working with distributions, beginning with the probability mass function. As an example, let's take a look at the binomial distribution. This is defined as\n",
    "\n",
    "$$\n",
    "f(k; n, p) = \\binom{n}{k} p^k q^{n-k}\n",
    "$$\n",
    "\n",
    "with $q=1-p$. Say we have a process with a 30% chance of success; $f$ tells us how likely it is to get $k$ successes out of $n$ independent trials.\n",
    "\n",
    "**scipy** has analytical functions for a really wide range of distributions and probability mass functions; you can [find them here](https://docs.scipy.org/doc/scipy/reference/stats.html). To get the binomial, we'll use `scipy.stats.binom`. \n",
    "\n",
    "There are two ways to call different distributions. You can declare a random variable object first, for example, `rv = binom(n, p)`, and then call `rv.pmf(k)` on it. Or you can call it all in one go via `binom.pmf(k, n, p)`. Here it is using the former:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 20\n",
    "p = 0.3\n",
    "rv = st.binom(n, p)\n",
    "k = np.arange(0, 15)\n",
    "\n",
    "# Plot\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(k, rv.pmf(k), \"bo\", ms=8)\n",
    "ax.vlines(k, 0, rv.pmf(k), colors=\"b\", linestyles=\"-\", lw=1)\n",
    "ax.set_title(f\"Binomial pmf: $n$={n}, $p$={p}\", loc=\"left\")\n",
    "ax.set_xlabel(\"k\")\n",
    "ax.set_ylabel(\"Probability\")\n",
    "ax.set_xlim(0, None)\n",
    "ax.set_ylim(0, None)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Likewise, we can access the **cumulative distribution function**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.plot(k, rv.cdf(k))\n",
    "ax.scatter(k, rv.cdf(k), s=50)\n",
    "ax.axhline(1, color=\"k\", alpha=0.7, linestyle=\"-.\", lw=1)\n",
    "ax.set_title(f\"Binomial cdf: $n$={n}, $p$={p}\", loc=\"left\")\n",
    "ax.set_xlabel(\"k\")\n",
    "ax.set_ylabel(\"Probability\")\n",
    "ax.set_xlim(0, None)\n",
    "ax.set_ylim(0, 1);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Of course, **continuous random variables** are also covered. To get a wide range of pdfs, the commands are `scipy.stats.distributionname.pdf(x, parameters=)`.\n",
    "\n",
    "Let's see a couple of examples. The lognormal distribution is given by $f(x, s) = \\frac{1}{sx\\sqrt{2\\pi}}\\exp\\left(-\\frac{\\ln^2(x)}{2s^2}\\right)$ and the gamma by $f(x, a) = \\frac{x^{a-1}e^{-x}}{\\Gamma(a)}$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s = 0.5\n",
    "a = 2\n",
    "\n",
    "x = np.linspace(0, 6, 500)\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(x, st.lognorm.pdf(x, s), label=f\"Lognormal: s={s}\")\n",
    "ax.plot(x, st.gamma.pdf(x, a), label=f\"Gamma: a={a}\")\n",
    "ax.set_xlabel(\"x\")\n",
    "ax.set_ylabel(\"PDF\")\n",
    "ax.set_ylim(0, 1)\n",
    "ax.set_xlim(0, 6)\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Likewise, to get the cdf for a given distribution, the command is `scipy.stats.distributionname.cdf(x, parameters=)`. Here are the ones for the lognormal and gamma."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.linspace(0, 6, 500)\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(x, st.lognorm.cdf(x, s), label=f\"Lognormal: s={s}\")\n",
    "ax.plot(x, st.gamma.cdf(x, a), label=f\"Gamma: a={a}\")\n",
    "ax.set_xlabel(\"x\")\n",
    "ax.set_ylabel(\"CDF\")\n",
    "ax.set_ylim(0, 1.2)\n",
    "ax.set_xlim(0, 6)\n",
    "ax.axhline(1, color=\"k\", alpha=0.7, linestyle=\"-.\", lw=1)\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Other properties of PMFs and PDFs\n",
    "\n",
    "A range of functions are available for PMFs and PDFs in addition to the ones we've seen already. For a pmf or pdf, we can call `median`, `mean`, `var`, `std`, and so on. Let's see an example with two of the most useful: interval and percentile.\n",
    "\n",
    "`interval(alpha, ...)` gives the endpoints of the range around the median that contain alpha percent of the distribution. `ppf(q, ...)` gives the quantiles of a given distribution, defined as $F(x) = P(X\\leq x) = q$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = np.linspace(-4, 4, 500)\n",
    "y = st.norm.pdf(x)\n",
    "\n",
    "# Get percentiles\n",
    "quantiles = [0.25, 0.5, 0.75]\n",
    "probs = [st.norm.ppf(q) for q in quantiles]\n",
    "# Interval\n",
    "x1, x2 = st.norm.interval(0.95)\n",
    "cut_x = x[((x > x1) & (x < x2))]\n",
    "cut_y = y[((x > x1) & (x < x2))]\n",
    "\n",
    "# Plot\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(x, y)\n",
    "for i, prob in enumerate(probs):\n",
    "    ax.plot([prob, prob], [0, st.norm.pdf(prob)], lw=0.8, color=\"k\", alpha=0.4)\n",
    "    ax.annotate(\n",
    "        f\"q={quantiles[i]}\",\n",
    "        xy=(prob, st.norm.pdf(prob)),\n",
    "        xycoords=\"data\",\n",
    "        xytext=(-10, 30),\n",
    "        textcoords=\"offset points\",\n",
    "        arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"angle3,angleA=0,angleB=-90\"),\n",
    "        # fontsize=12,\n",
    "    )\n",
    "ax.fill_between(cut_x, 0, cut_y, alpha=0.2, label=r\"95% interval\")\n",
    "ax.set_xlabel(\"x\")\n",
    "ax.set_ylabel(\"PDF\")\n",
    "ax.set_xlim(-4, 4)\n",
    "ax.set_ylim(0, 0.55)\n",
    "ax.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Randomness for computers\n",
    "\n",
    "Computers love instruction and hate ambiguity. As such, randomness is quite tricky for them. So tricky, that no computer is able to produce *perfectly* random numbers but instead only has a **pseudo-random number generator**, or PRNG. As far as humans go, these are pretty good and modern ones are so good that using them is unlikely to be an issue unless you really are working at the frontiers of the science of randomness.\n",
    "\n",
    "**numpy** uses a PRNG that's a 64-bit Permuted Congruential Generator, though you can access other generators too. Here's how to call it to generate $x \\thicksim \\mathcal{U}(0,1)$,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy.random import default_rng\n",
    "\n",
    "rng = default_rng()\n",
    "rng.random(size=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the above, `rng` is an object that you can call many random number generating functions on. Here we just asked for 2 values drawn from between 0 and 1. \n",
    "\n",
    "If you are using **pandas** for your analysis, then it comes with random sampling methods built in under the guise of `df.sample()` for a dataframe `df`. This has keywords for number of samples (`n`) **or** fraction of all rows to sample (`frac`) and whether to use `weights=`. You can also pass a PRNG to the `.sample()` method.\n",
    "\n",
    "Another really useful random generator provides integers and is called `integers`. Let's see this but in the case where we're asking for a more elaborately shaped output array, a 3x3x2 dimensional tensor:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "min_int, max_int = 1, 20\n",
    "rng.integers(min_int, max_int, size=(3, 3, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One random function that is incredibly useful is `choice`, which returns a random selection from another type of object. Here, we show this by passing a list of letters and asking for two of them to be picked randomly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rng.choice([\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"], size=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This choice can also be made with a given probability. Let's make a very large number of draws with an exponentially falling probability and see what we get!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_draws = 1000\n",
    "# Create 6 values spread across several orders of magnitude\n",
    "prob = np.logspace(0, -3, num=6)\n",
    "# Normalise this to 1\n",
    "prob = prob / sum(prob)\n",
    "# Choose the letters\n",
    "letter_choices = rng.choice([\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"], size=num_draws, p=prob)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To make it easy to see what happened, we'll use the in-built collections library's `Counter` function to go from a long list of all of the letters to a dictionary of letters and counts of how frequently they occurred. We'd like to have the bars in order but `Counter` doesn't do that automatically, so we have to do a few things around the `counts` dictionary to change this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import Counter, OrderedDict\n",
    "\n",
    "counts = OrderedDict(sorted(Counter(letter_choices).items()))\n",
    "plt.bar(counts.keys(), counts.values());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As expected, 'a' was chosen many more times than 'b', and so on. In fact, if we divided the counts by `num_draws`, we would find that the probability of each letter was converging toward the probabilities we provided in `prob`.\n",
    "\n",
    "Another useful random function to know about is `shuffle`, and you can probably guess what it does! But note that it does the shuffling to the list you put in, rather than returning a new, modified list. Here's an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plain_list = [\"This\", \"list\", \"is\", \"well\", \"ordered.\"]\n",
    "rng.shuffle(plain_list)\n",
    "plain_list"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Reproducibility\n",
    "\n",
    "If you need to create random numbers reproducibly, then you can do it by setting a seed value like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "seed_for_prng = 78557\n",
    "prng = np.random.default_rng(seed_for_prng)  # prng=probabilistic random number generator\n",
    "prng.integers(0, 10, size=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prng = np.random.default_rng(seed_for_prng)\n",
    "prng.integers(0, 10, size=2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The seed tells the generator where to start, so by passing the same seed in we can make the random numbers begin in the same place. The `prng` above can also be passed to some functions as a keyword argument.\n",
    "\n",
    "### Random numbers drawn from distributions\n",
    "\n",
    "Using **numpy**, we can draw samples from distributions using the `prng.distribution` syntax. One of the most common distributions you might like to draw from is the uniform, for example\n",
    "\n",
    "$$\n",
    "x \\thicksim \\mathcal{U}(0, 10)\n",
    "$$\n",
    "\n",
    "with, here, a minimum of 0 and a maximum of 10. Here's the code:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prng.uniform(low=0, high=10, size=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see how to draw from one other important distribution function: the Gaussian, or normal, distribution $x \\thicksim \\mathcal{N}\\left(\\mu, \\sigma\\right)$ and check that it looks right. We'll actually do two different ones: a standard normal, with $\\mu=0$ and $\\sigma=1$, and a shifted, relaxed one with different parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def gauss(x):\n",
    "    \"\"\"Analytical Gaussian.\"\"\"\n",
    "    return (1 / np.sqrt(2 * np.pi)) * np.exp(-0.5 * x ** 2)\n",
    "\n",
    "\n",
    "# Make the random draws\n",
    "num_draws = 10000\n",
    "vals = prng.standard_normal(num_draws)\n",
    "\n",
    "# Get analytical solution\n",
    "x_axis_vals = np.linspace(-3, 3, 300)\n",
    "analytic_y = gauss(x_axis_vals)\n",
    "\n",
    "# Random draws of shifted/flatter dist\n",
    "mu = 0.5\n",
    "sigma = 2\n",
    "vals_shift = prng.normal(loc=mu, scale=sigma, size=num_draws)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.plot(x_axis_vals, analytic_y, label=\"Std norm: analytical\", lw=3)\n",
    "ax.hist(vals, bins=50, label=\"Std norm: generated\", density=True, alpha=0.8)\n",
    "ax.hist(\n",
    "    vals_shift,\n",
    "    bins=50,\n",
    "    label=f\"Norm: $\\mu$={mu}, $\\sigma$={sigma}\",\n",
    "    density=True,\n",
    "    alpha=0.8,\n",
    ")\n",
    "ax.legend(frameon=False)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The Monte Carlo Method\n",
    "\n",
    "Monte Carlo is the name of a part of Monaco that harbours a famous casino, yes, but it's also the name given to a bunch of techniques that rely on generating random numbers in order to solve problems. It's a really useful technique that entire textbooks cover and we can't hope to give it the love and attention it requires here, covering as it does Bayesian statistics, random walks, Markov switching models, Markov Chain Monte Carlo, bootstrapping, and optimisation! But what we can do is take a quick look at the very, very core code tools that can support these applications. The bottom line is that between the drawing of random variables from given **scipy** distributions we've already seen, the use of `prng.choice()`, and the use of `prng.uniform`, a lot of Monte Carlo methods are covered.\n",
    "\n",
    "We already covered drawing random numbers from distributions already included in **scipy**.\n",
    "\n",
    "`prng.uniform` is helpful in the following case: in the (extremely unlikely) event that there isn't a pre-built distribution available for a case where you know the analytical expression of a PDF and its CDF, a quick way to get random numbers distributed according to that PDF is to plug random numbers into the inverse cumulative distribution function. ie you plug random numbers $r$ into $\\text{cdf}^{-1}(r)$ in order to generate $x \\thicksim \\text{pdf}$. The random numbers you plug in must come from a uniform distribution between 0 and 1.\n",
    "\n",
    "`prng.choice()` comes into its own for simulation, one of the many applications of Monte Carlo techniques in economics. (I mean simulation loosely here; it could be an agent-based model, it could be simulating an econometric relationship.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's do a very simple and canonical example of a simulation using `.choice()`: rolling a 6-sided die...\n",
    "\n",
    "..but we want to make it a *bit* more exciting than that! Let's see two die, one that's fair (equal probability of getting any value in 1 to 6) and one that's loaded (in this case, we'll make a 6 twice as likely as other values).\n",
    "\n",
    "For a naive estimate of the probability of a particular die score based on simulation, it's going to be\n",
    "\n",
    "$$\n",
    "\\hat{p}_\\omega = \\frac{\\text{Counts}_\\omega}{\\text{Total counts}}\n",
    "$$\n",
    "\n",
    "with $\\omega \\in \\{1, 2, 3, 4, 5, 6\\}$.\n",
    "\n",
    "To simulate this, we'll use the `choice` function fed with the six values, 1 to 6, on some dice. Then we'll count the occurrences of each, creating a dictionary of keys and values with `Counter`, and then plot those.\n",
    "\n",
    "To work out the (estimate of) probability based on the simulation, we've divided the number of throws per value by the total number of throws. You can see that with so many throws, there's quite a wedge between the chance of obtaining a six in both cases. Meanwhile, the fair die is converging to the dotted line, which is $1/6$. Note that because of the individual probabilities summing to unity, a higher probability of a six on the loaded die means that values 1 to 5 must have a lower probability than with the fair die; and you can see that emerging in the chart too.\n",
    "\n",
    "In doing this for every possible outcome, we're effectively estimating a probability mass function.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "throws = 1000\n",
    "die_vals = np.arange(1, 7)\n",
    "probabilities = [1 / 7, 1 / 7, 1 / 7, 1 / 7, 1 / 7, 2 / 7]\n",
    "fair_throws = prng.choice(die_vals, size=throws)\n",
    "load_throws = prng.choice(die_vals, size=throws, p=probabilities)\n",
    "\n",
    "\n",
    "def throw_list_to_array(throw_list):\n",
    "    # Count frequencies of what's in throw list but order the dictionary keys\n",
    "    counts_dict = OrderedDict(sorted(Counter(throw_list).items()))\n",
    "    # Turn the key value pairs into a numpy array\n",
    "    array = np.array(\n",
    "        [list(counts_dict.keys()), list(counts_dict.values())], dtype=float\n",
    "    )\n",
    "    # Divide counts per value by num throws\n",
    "    array[1] = array[1] / len(throw_list)\n",
    "    return array\n",
    "\n",
    "\n",
    "counts_fair = throw_list_to_array(fair_throws)\n",
    "counts_load = throw_list_to_array(load_throws)\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "ax.scatter(counts_fair[0], counts_fair[1], color=\"b\", label=\"Fair\")\n",
    "ax.scatter(counts_load[0], counts_load[1], color=\"r\", label=\"Loaded\")\n",
    "ax.set_xlabel(\"Die value\")\n",
    "ax.set_ylabel(\"Probability\")\n",
    "ax.axhline(1 / 6, color=\"k\", alpha=0.3, linestyle=\"-.\", lw=0.5)\n",
    "ax.legend(frameon=True, loc=\"upper left\")\n",
    "ax.set_ylim(0.0, 0.4);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's estimate the probability mass functions for our dice using the `cumsum` function: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots()\n",
    "ax.plot(\n",
    "    counts_fair[0],\n",
    "    np.cumsum(counts_fair[1]),\n",
    "    color=\"b\",\n",
    "    label=\"Fair\",\n",
    "    marker=\"o\",\n",
    "    ms=10,\n",
    ")\n",
    "ax.plot(\n",
    "    counts_load[0],\n",
    "    np.cumsum(counts_load[1]),\n",
    "    color=\"r\",\n",
    "    label=\"Loaded\",\n",
    "    marker=\"o\",\n",
    "    ms=10,\n",
    ")\n",
    "ax.set_xlabel(\"Die value\")\n",
    "ax.set_ylabel(\"Cumulative distribution function\")\n",
    "ax.axhline(1, color=\"k\", alpha=0.3, linestyle=\"-.\", lw=0.5)\n",
    "ax.legend(frameon=True, loc=\"lower right\")\n",
    "ax.set_ylim(0.0, 1.2);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can see that the cumulative distribution function also tells a story about what's going on; namely, there is a lower gradient up to $i=6$, followed by a higher gradient. The two distributions are visually distinct.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fitting a probability distribution\n",
    "\n",
    "Often we are in a situation where we are working with empirical data and we want to know if a particular distribution function provides a good fit for a variable. **scipy** has a neat 'fit' function that can do this for us, given a guess at a distribution. This fit is computed by maximising a log-likelihood function, with a penalty applied for samples outside of range of the distribution.\n",
    "\n",
    "Let's see this in action with an example using synthetic data created from a noisy normal distribution:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "size = 1000\n",
    "μ, σ = 2, 1.5\n",
    "# Generate normally dist data\n",
    "data = prng.normal(loc=μ, scale=σ, size=size)\n",
    "# Add noise\n",
    "data = data + prng.uniform(-0.5, 0.5, size)\n",
    "# Show first 5 entries\n",
    "data[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Plot a histogram of the data and fit a normal distribution\n",
    "sns.distplot(data, bins=60, kde=False, fit=st.norm)\n",
    "# Get the fitted parameters as computed by scipy\n",
    "(est_loc, est_scale) = st.norm.fit(data)\n",
    "plt.legend(\n",
    "    [\n",
    "        f\"Est. normal dist. ($\\hat{{\\mu}}=${est_loc:.2f} and $\\hat{{\\sigma}}=${est_scale:.2f} )\",\n",
    "        \"Histogram\",\n",
    "    ],\n",
    "    loc=\"upper left\",\n",
    "    frameon=False,\n",
    ")\n",
    "fig = plt.figure()\n",
    "res = st.probplot(data, plot=plt)\n",
    "plt.show();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you can see, in this case the estimate $\\mu$ and $\\sigma$ are pretty close to the true values. The probability plot, the second chart shown, is very useful in practice because it shows how the often problematic tails are behaving."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Review\n",
    "\n",
    "In this very short introduction to probability and random processes with code, you should have learned how to:\n",
    "\n",
    "- ✅ use a wide range of probability density functions and probability mass functions from **scipy**;\n",
    "- ✅ use a psuedo-random number generator for drawing samples from distributions (and more!);\n",
    "- ✅ use a psuedo-random number generator reproducibly; \n",
    "- ✅ use **scipy** to fit data to a given distribution using maximum likelihood estimation; and\n",
    "- ✅ perform simulations using a psuedo-random number generator."
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "interpreter": {
   "hash": "e82e9306cec5f3813db66e68c531c869f324183486c55e9589deb7f101067873"
  },
  "kernelspec": {
   "display_name": "Python 3.8.12 64-bit ('codeforecon': conda)",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
